﻿Imports GBDZafiro
Public Class frmPerfil

    Dim dtPerfil As DataTable

    Private Sub frmPerfil_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        tvPerfil.Enabled = True
        ' MyBase.bnNuevo_Click(sender, e)
        cargarComboPerfil()
        clearArbol()
        cbPerfil.Text = ""
        ' tvPerfil.ImageList = ilPerfil
    End Sub

    Sub cargarComboPerfil()
        dtPerfil = GBDZafiro.Perfil.ConsultarAll()
        Dim ds As New DataSet
        ds.Tables.Add(dtPerfil)
        cbPerfil.DataSource = ds.Tables(0)
        cbPerfil.DisplayMember = "PERFIL"
        cbPerfil.ValueMember = "PERFIL"
    End Sub


    Sub cargarArbol()
        Dim dtMenu As DataTable = GBDZafiro.Menu.ConsultarAll()
        Dim drMenu As DataRow
        Dim i = dtMenu.Rows.Count

        While i > 0
            drMenu = dtMenu.Rows.Item(i - 1)
            If DBNull.Value.Equals(drMenu("PADRE")) Then
                Dim root As New TreeNode(drMenu("TITULO"))
                root.Tag = drMenu("COD_MENU")
                tvPerfil.Nodes.Add(root)
                crearHojas(dtMenu, root, drMenu("COD_MENU").ToString())
                root.ExpandAll()
            End If
            i = i - 1
        End While

    End Sub

    Sub crearHojas(ByVal dtMenu As DataTable, ByRef nodoPadre As TreeNode, codMenu As String)
        For Each drMenu As DataRow In dtMenu.Rows
            If drMenu("PADRE").Equals(codMenu) And _
                Not drMenu("COD_MENU").Equals(drMenu("PADRE")) Then
                Dim nodoHijo As New TreeNode(drMenu("TITULO"))
                nodoHijo.Tag = drMenu("COD_MENU")
                'nodoHijo.SelectedImageIndex = Nothing
                nodoPadre.Nodes.Add(nodoHijo)
                crearHojas(dtMenu, nodoHijo, drMenu("COD_MENU"))
            End If
        Next
    End Sub

    '##################### Evento del treeview cuando se checkea

    Private Sub TreeView1_AfterCheck(ByVal sender As Object, ByVal e As TreeViewEventArgs) Handles tvPerfil.AfterCheck
        RemoveHandler tvPerfil.AfterCheck, AddressOf TreeView1_AfterCheck

        Call CheckAllChildNodes(e.Node)

        If e.Node.Checked Then
            If e.Node.Parent Is Nothing = False Then
                Dim allChecked As Boolean = True
                Call IsEveryChildChecked(e.Node.Parent, allChecked)
                If allChecked Then
                    e.Node.Parent.Checked = True
                    Call ShouldParentsBeChecked(e.Node.Parent)
                End If
            End If
        Else
            Dim parentNode As TreeNode = e.Node.Parent
            While parentNode Is Nothing = False
                parentNode.Checked = False
                parentNode = parentNode.Parent
            End While
        End If

        AddHandler tvPerfil.AfterCheck, AddressOf TreeView1_AfterCheck
    End Sub

    Private Sub CheckAllChildNodes(ByVal parentNode As TreeNode)
        For Each childNode As TreeNode In parentNode.Nodes
            childNode.Checked = parentNode.Checked
            CheckAllChildNodes(childNode)
        Next
    End Sub

    Private Sub IsEveryChildChecked(ByVal parentNode As TreeNode, ByRef checkValue As Boolean)
        For Each node As TreeNode In parentNode.Nodes
            Call IsEveryChildChecked(node, checkValue)
            If Not node.Checked Then
                checkValue = False
            End If
        Next
    End Sub

    Private Sub ShouldParentsBeChecked(ByVal startNode As TreeNode)
        If startNode.Parent Is Nothing = False Then
            Dim allChecked As Boolean = True
            Call IsEveryChildChecked(startNode.Parent, allChecked)
            If allChecked Then
                startNode.Parent.Checked = True
                Call ShouldParentsBeChecked(startNode.Parent)
            End If
        End If
    End Sub

    '################################################################fin evento del treeview 

    '################################################################ Eventos Controles
    Protected Overrides Sub bnNuevo_Click(sender As System.Object, e As System.EventArgs)
        MyBase.bnNuevo_Click(sender, e)
        cargarComboPerfil()
        cbPerfil.DropDownStyle = ComboBoxStyle.DropDown
        cbPerfil.Text = ""
        clearArbol()
        cbPerfil.Focus()
    End Sub

    Protected Overrides Sub bnGuardar_Click(sender As System.Object, e As System.EventArgs)
        If addUpdatePerfil() Then
            cargarComboPerfil()
            tbDescripcion.Clear()
            'addRowcb()
            MyBase.bnGuardar_Click(sender, e)
        End If
    End Sub

    Protected Overrides Sub bnEliminar_Click(sender As System.Object, e As System.EventArgs)
        Dim perfil As GBDZafiro.Perfil = crearPerfil()
        deletePerfil(perfil)
        'cbPerfil.Items.Remove(cbPerfil.SelectedValue)
        deleteItemcb()
        MyBase.bnEliminar_Click(sender, e)
    End Sub

    Protected Overrides Sub bnCancelar_Click(sender As System.Object, e As System.EventArgs)
        MyBase.bnCancelar_Click(sender, e)
        clearArbol()


        If Not dtPerfil Is Nothing Then
            actualizarArbol()
        End If

        cbPerfil.Enabled = True
        cbPerfil.Text = ""
        tvPerfil.Enabled = True

    End Sub

    Protected Overrides Sub bnEditar_Click(sender As System.Object, e As System.EventArgs)
        MyBase.bnEditar_Click(sender, e)
        actualizarArbol()
        'cargarComboPerfil()
    End Sub

    Private Sub cbPerfil_SelectionChangeCommitted(sender As System.Object, e As System.EventArgs) Handles cbPerfil.SelectionChangeCommitted
        actualizarArbol()
        'tbDescripcion.Enabled = True
    End Sub

    Private Sub cbPerfil_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles cbPerfil.SelectedIndexChanged
        'actualizarArbol()
    End Sub

    '################################################################ Fin Eventos Controles

    '################################################################ Metodos para Controles

    Private Sub clearArbol()
        tvPerfil.Nodes.Clear()
        cargarArbol()
    End Sub

    Private Sub actualizarArbol()
        Dim dtMenuPerfil As DataTable
        Dim mPerfil As New GBDZafiro.Menu_Perfil
        For Each rowPerfil As DataRow In dtPerfil.Rows
            If rowPerfil("PERFIL").Equals(cbPerfil.SelectedValue) Then
                cbPerfil.DropDownStyle = ComboBoxStyle.DropDownList
                tbDescripcion.Text = rowPerfil("DESCRIPCION")
            End If
        Next

        clearArbol()

        mPerfil.perfil = cbPerfil.Text
        dtMenuPerfil = GBDZafiro.Menu_Perfil.ConsxPerfil(mPerfil)

        RemoveHandler tvPerfil.AfterCheck, AddressOf TreeView1_AfterCheck
        For Each rowMenuPerfil As DataRow In dtMenuPerfil.Rows
            For Each nodo As TreeNode In tvPerfil.Nodes
                If nodo.Tag.Equals(rowMenuPerfil("COD_MENU")) Then
                    nodo.Checked = True
                    checkArbol(nodo, dtMenuPerfil)
                End If
            Next
        Next
        AddHandler tvPerfil.AfterCheck, AddressOf TreeView1_AfterCheck
    End Sub

    Private Sub checkArbol(ByRef nodoPadre As TreeNode, ByRef dtMenuPerfil As DataTable)
        For Each rowMenuPerfil As DataRow In dtMenuPerfil.Rows
            For Each nodoHijo As TreeNode In nodoPadre.Nodes
                If nodoHijo.Tag.Equals(rowMenuPerfil("COD_MENU")) Then
                    nodoHijo.Checked = True
                    checkArbol(nodoHijo, dtMenuPerfil)
                End If
            Next
        Next
    End Sub

    Private Sub deleteItemcb()
        For Each row As DataRow In dtPerfil.Rows
            If row("PERFIL").Equals(cbPerfil.SelectedValue) Then
                dtPerfil.Rows.Remove(row)
                Exit For
            End If
        Next
    End Sub

    Private Sub addRowcb()
        Dim row = dtPerfil.NewRow
        row("PERFIL") = cbPerfil.Text
        row("DESCRIPCION") = cbPerfil.Text
        dtPerfil.Rows.Add(row)
    End Sub

    Private Function verificarCampos() As Boolean
        If tbDescripcion.TextLength < 1 Or cbPerfil.Text.Length < 1 Then
            Return True
        Else
            Return False
        End If

    End Function

    Private Function crearPerfil() As GBDZafiro.Perfil
        Dim perfil As New GBDZafiro.Perfil
        perfil.perfil = cbPerfil.Text
        perfil.descripcion = tbDescripcion.Text
        Return perfil
    End Function

    Private Function cargarListaMenuPerfil(ByRef perfil As GBDZafiro.Perfil) As List(Of GBDZafiro.Menu_Perfil)
        Dim lMenuPerfil As New List(Of GBDZafiro.Menu_Perfil)
        For Each node As TreeNode In tvPerfil.Nodes
            crearLMenuPerfil(node, lMenuPerfil, perfil)
        Next
        Return lMenuPerfil
    End Function

    Private Sub crearLMenuPerfil(ByRef nodePadre As TreeNode, ByRef lMenuPerfil As IList(Of GBDZafiro.Menu_Perfil), ByRef perfil As GBDZafiro.Perfil)
        If Not nodePadre Is Nothing Then
            If nodePadre.Checked And Not verificarLista(nodePadre, lMenuPerfil) Then
                Dim menuPerfil As New GBDZafiro.Menu_Perfil
                menuPerfil.cod_Menu = nodePadre.Tag
                menuPerfil.perfil = perfil.perfil
                lMenuPerfil.Add(menuPerfil)
                addNodosPadreslMenuPerfil(nodePadre.Parent, lMenuPerfil, perfil)
                'For Each nodoHijo As TreeNode In nodePadre.Nodes
                '    crearLMenuPerfil(nodoHijo, lMenuPerfil, perfil)
                'Next               
            End If
            For Each nodoHijo As TreeNode In nodePadre.Nodes
                crearLMenuPerfil(nodoHijo, lMenuPerfil, perfil)
            Next
        End If
    End Sub

    Private Function verificarLista(node As TreeNode, ByRef lMenuPerfil As IList(Of GBDZafiro.Menu_Perfil)) As Boolean
        For Each menuPerfil As GBDZafiro.Menu_Perfil In lMenuPerfil
            If StrComp(menuPerfil.cod_Menu, node.Tag) = 0 And node Is Nothing = False Then
                Return True
                Exit Function
            End If
        Next
        Return False
    End Function

    Private Sub addNodosPadreslMenuPerfil(ByRef nodoPadre As TreeNode, ByRef lMenuPerfil As IList(Of GBDZafiro.Menu_Perfil), ByRef perfil As GBDZafiro.Perfil)
        If Not nodoPadre Is Nothing Then
            If Not verificarLista(nodoPadre, lMenuPerfil) Then
                Dim menuPerfil As New GBDZafiro.Menu_Perfil
                menuPerfil.cod_Menu = nodoPadre.Tag
                menuPerfil.perfil = perfil.perfil
                lMenuPerfil.Add(menuPerfil)

                addNodosPadreslMenuPerfil(nodoPadre.Parent, lMenuPerfil, perfil)
            End If
        End If
    End Sub

    Private Function addUpdatePerfil() As Boolean
        Dim perfil As GBDZafiro.Perfil = crearPerfil()
        If Not GBDZafiro.Perfil.existPerfil(perfil) Then
            If verificarCampos() Then
                MessageBox.Show("Digite los campos perfil y descripción ", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Return False
                Exit Function
            Else
                addPerfil(perfil)
            End If

        Else
            If verificarCampos() Then
                MyBase.msnBoxInformacion("Digite los campos perfil y descripción ")
                Return False
                Exit Function
            Else
                updatePerfil(perfil)
            End If
        End If
        Return True
    End Function

    Private Sub addPerfil(ByRef perfil As GBDZafiro.Perfil)
        Dim lMenuPerfil As List(Of GBDZafiro.Menu_Perfil)
        GBDZafiro.Perfil.Nuevo(perfil) ''agrego el perfil
        lMenuPerfil = cargarListaMenuPerfil(perfil)
        GBDZafiro.Menu_Perfil.Nuevo(lMenuPerfil)
        'MessageBox.Show("Digite el usuario", "Información", MessageBoxButtons.OK, MessageBoxIcon.Information)
        MyBase.msnBoxInformacion("Perfil Guardado")
    End Sub

    Private Sub updatePerfil(perfil As GBDZafiro.Perfil)
        Dim mPerfil As New GBDZafiro.Menu_Perfil
        Dim lMenuPerfil As List(Of GBDZafiro.Menu_Perfil)

        mPerfil.perfil = perfil.perfil
        GBDZafiro.Menu_Perfil.Eliminar(mPerfil)

        lMenuPerfil = cargarListaMenuPerfil(perfil)
        GBDZafiro.Menu_Perfil.Nuevo(lMenuPerfil)
        MyBase.msnBoxInformacion("Perfil Actualizado")
    End Sub

    Private Sub deletePerfil(perfil As GBDZafiro.Perfil)
        If GBDZafiro.Perfil.existPerfil(perfil) Then
            If GBDZafiro.Usuario.existPerfilUsuario(perfil) Then
                MyBase.msnBoxWarning("Uno o varios usuarios usan el perfil " + perfil.perfil _
                                     + ", cambiar el perfil a estos")
            Else
                Dim mPerfil As New GBDZafiro.Menu_Perfil
                mPerfil.perfil = perfil.perfil
                GBDZafiro.Menu_Perfil.Eliminar(mPerfil)
                GBDZafiro.Perfil.Eliminar(perfil)
                MyBase.msnBoxInformacion("Perfil Borrado")
            End If

        Else
            If Not perfil.perfil.Length < 1 Then
                MyBase.msnBoxExcla("El usuario no existe")
            End If
        End If
    End Sub

    '################################################################ Fin Metodos para Controles   

End Class
